package com.zyt.wiki.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.zyt.wiki.filter.MyHttpRequestWrapper;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/***
 * HttpServletRequest过滤器，将request对象重新封装，以便后续可以多次读取流
 * 	    解决: request.getInputStream()只能读取一次的问题
 * 	    目标: 流可重复读
 */
@Component
@WebFilter(filterName = "HttpServletRequestFilter", urlPatterns = "/")	// 设置url匹配模式，过滤器名称
public class HttpServletRequestFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 根据request，创建自定义request包装器，其中将流数据缓存到了属性内存中，实现了流可重复读
        ServletRequest requestWrapper = null ;
        if(request instanceof HttpServletRequest) {
            requestWrapper = new MyHttpRequestWrapper((HttpServletRequest)request) ;
        }
        // 在FilterChain中传递新的request对象
        if(null == requestWrapper) {
            chain.doFilter(request, response);
        }else {
            chain.doFilter(requestWrapper, response);
        }
    }

}
